package com.game.units {
	import com.game.data.Data;
	import flash.display.BitmapData;
	import flash.display.Graphics;
	import flash.geom.Matrix;
	public class EnemyGraphics {
		private static const SLICE_SPEED:Number=18;
		private static const ANGLE_ADJ:Number=(1 / 180) * Math.PI;
		public var size:int=Data.STEP;
		public var padding:int=Data.IMAGE_PADDING;
		private var _graphics:Graphics;
		private var _bmp:BitmapData=new BitmapData(size + padding, size + padding, true, 0);
		private var _animBmp:BitmapData=new BitmapData(size + padding, size + padding, true, 0);
		private var _matrix:Matrix=new Matrix();
		private var _dir:int=0;
		private var _duration:Number=0;
		private var _targetAngle:Number=0;
		private var _rotation:Number=0;
		private var _animationCounter:int=0;
		private var _animationLength:int=0;
		private var _animationDelay:int=0;
		private var _type:int=0;
		public function EnemyGraphics(graphics:Graphics) {
			_graphics=graphics;
			_graphics.beginBitmapFill(_bmp, new Matrix(1, 0, 0, 1, -(size + padding) / 2, -(size + padding) / 2), false, true);
			_graphics.drawRect(-(size + padding) / 2, -(size + padding) / 2, size + padding, size + padding);
			_graphics.endFill();
		}
		public function init(type:int):void {
			_type=type;
			_targetAngle=_rotation=-Math.PI / 2;
			_animationCounter=0;
			_animationDelay=0;
			_animationLength=Data.getInstance().enemyAnimArray[type].length;
			_animBmp=Data.getInstance().enemyAnimArray[type][_animationCounter];
		}
		public function move():void {
			_duration-=ANGLE_ADJ;
			if (_duration > 0) {
				_rotation+=SLICE_SPEED * ANGLE_ADJ * _dir;
			} else {
				_rotation=_targetAngle;
			}
		}
		public function redraw():void {
			if (int(_rotation * 100) != int(Math.acos(_matrix.a) * 100) || _animationLength > 1) {
				_animBmp=Data.getInstance().enemyAnimArray[_type][_animationCounter];
				_bmp.unlock();
				_matrix.identity();
				_bmp.fillRect(_bmp.rect, 0x0);
				_matrix.translate(-(size + this.padding ) / 2, -(size + this.padding )/ 2);
				_matrix.rotate(_rotation);
				_matrix.translate((size + this.padding ) / 2, (size + this.padding ) / 2);
				_bmp.draw(_animBmp, _matrix, null, null, null, true);
				_bmp.lock();
			}
			_animationDelay++;
			if (_animationDelay >= 1) {
				_animationCounter++;
				_animationDelay=0;
			}
			if (_animationCounter > _animationLength - 1) {
				_animationCounter=0;
			}
		}
		public function turn(ang:Number):void {
			_targetAngle=ang;
			var dist:Number=_rotation - ang;
			if (dist >= 0) {
				if (dist > Math.PI) {
					_dir=1;
					dist-=Math.PI * 2;
				} else {
					_dir=-1;
				}
			} else {
				if (dist < -Math.PI) {
					_dir=-1;
					dist+=Math.PI * 2;
				} else {
					_dir=1;
				}
			}
			//Math.abs
			_duration=(dist / SLICE_SPEED) < 0 ? -(dist / SLICE_SPEED) : (dist / SLICE_SPEED);
		}
	}
}